<?php
include_once "inc/cLog.php";

// Page only needs to call this function to get things going with db
function db_init() {
	$db_link = db_connect();
	if(!$db_link) {
		die('Could not connect: ' . mysql_error());
	}

	db_initialize();

	return $db_link;
}

function db_connect() {
	global $settings;

	//echo "db_connect()<br>";
	$db_user = 'dispatch';
	$db_pass = 'dispatchpw';

	$db_link = mysql_connect($settings["server_mysql"], $db_user, $db_pass);
	if(!$db_link) {
	    echo "Could not connect: " .mysql_error(). "<br>";
	}

	return $db_link;
}

function db_initialize() {
	// select the database
	$query = "use dispatch";
	$result = mysql_query($query);
	if(!$result) {
		die("unable to select db");
	}
}

function db_list_set($list, $id, $data, $value) {
	global $log;
	if(!(strpos($data, "track") !== false)) {
		if(!(strpos($data, "dn_curr") !== false)) {
			$log->write("[$id] list_set($data, $value)");
		}
	}
	$query = "UPDATE $list set $data='$value' WHERE"
			." id='$id'";
	//echo "$query\n";
	$result = db_query($query);
	if(!$result) {
		echo "error: wasn't able to set the status in the instance\n";
		exit(1);
	}
}

function db_isTable($tableName) {
	$query = "";
	$result = mysql_query($query);
	echo "TODO";
}

function db_createTable($query) {
	return db_query($query);
}

function db_query($query) {
	$result = mysql_query($query);
	if(!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "<br>";
		echo $message;
		echo "query: '$query'<br>";
	}

	return $result;
}

function db_instance_add($age, $ou) {
	$query = "INSERT INTO instance (dt, status, age, stale_dn, track) VALUES ("
		."'". date("Y-m-d h:m:s", time()) ."'"
		.", 'INIT'"
		.", $age"
		.", \"OU=$ou,DC=na,DC=micron,DC=com\""
		.", 1"
		.")";
	//echo "query is '$query'\n";

	$result = db_query($query);

	return $result;
}

function db_instance_set_list($id, $list) {
	$query = "UPDATE instance SET list='$list' WHERE"
				. " id='$id'";
	//echo "query is '$query'\n";

	$result = db_query($query);

	return $result;
}

// Change the status of the instance to 'FIRST_RUN'
function db_instance_set_status($id, $status) {
	$query = "UPDATE instance SET status='$status' WHERE"
				. " id='$id'";
	//echo "query is '$query'\n";

	$result = db_query($query);

	return $result;
}

function db_list_add($list) {
	// table: list
	$query = "CREATE TABLE $list ("
			."id INT PRIMARY KEY AUTO_INCREMENT"
			.", dt DATETIME"
			.", netbios VARCHAR(512)"
			.", dn_orig VARCHAR(512)"
			.", dn_curr VARCHAR(512)"
			.", isStale	BOOLEAN"
			.", isEnabled BOOLEAN"
			.", isPing BOOLEAN"
			.", wasLogon BOOLEAN"
			.", wasEnabled BOOLEAN"
			.", wasMoved BOOLEAN"
			.", wasDeleted BOOLEAN"
			.", isException BOOLEAN"
			.", isIgnore BOOLEAN"
			.", track INT default 0"
			.")";
	$result = db_createTable($query);
	return $result;
}

// Populate the list
function db_list_populate($table, $age) {
	//$start_node = "dc=ap,dc=micron,dc=com";
	//$start_node = "dc=ds,dc=micron,dc=com";
	//$start_node = "dc=eu,dc=micron,dc=com";
	$start_node = "dc=na,dc=micron,dc=com";

	// list of objects to populate into db
	$list = array();

	// load up stale objects
	$cmd = "dsquery computer \"$start_node\" -stalepwd $age -limit 0";
	$output = array();
	echo "Executing query ...\n";
	echo "- '$cmd'\n";
	exec($cmd, $output);
	$list = array_merge($list, $output);

	// load up '-old' objects
	$cmd = "dsquery computer \"$start_node\" -limit 0 -name \"*-old\"";
	$output = array();
	echo "Executing query ...\n";
	echo "- '$cmd'\n";
	exec($cmd, $output);
	$list = array_merge($list, $output);

	// load up '-retired' objects
	$cmd = "dsquery computer \"$start_node\" -limit 0 -name \"*-retired\"";
	$output = array();
	echo "Executing query ...\n";
	echo "- '$cmd'\n";
	exec($cmd, $output);
	$list = array_merge($list, $output);

	echo "Sorting object list ...\n";
	sort($list);

	echo "Removing duplicates ...\n";
	$list = array_unique($list);

	echo "Inserting results into DB ...\n";
	foreach($list as $next) {
		$parts = explode("\"", trim($next));
		$dn_orig = $parts[1];

		// Exclude the BMC Software OU
		if(strpos($dn_orig, "OU=BMC Software") !== false) {
			// this will skip this foreach iteration and jump to the next
			continue;
		}

		// pop off the netbios name
		$parts = explode(",", $dn_orig);
		$parts = explode("=", $parts[0]);
		//echo "netbios = $parts[1]\n";
		$netbios = $parts[1];

		$query = "INSERT INTO $table (dt, netbios, dn_orig, dn_curr, isStale, isEnabled, isPing, wasLogon, wasMoved, wasEnabled, wasDeleted, isException, isIgnore, track) VALUES ("
			."'". date("Y-m-d h:m:s", time()) ."'"
			.", \"$netbios\""
			.", \"$dn_orig\""
			.", \"$dn_orig\""
			.", true"
			.", false"
			.", false"
			.", false"
			.", false"
			.", false"
			.", false"
			.", false"
			.", false"
			.", 0"
			.")";

		// execute query and assume success
		db_query($query);
	}
	echo "Population complete.\n";
}

?>
